package com.house.wym.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.stereotype.Service;

@Service
public class AlipayService {

    // 支付宝网关
    private static final String ALIPAY_GATEWAY = "https://openapi.alipaydev.com/gateway.do";
    // 应用ID
    private static final String APP_ID = "9021000137697174";
    // 私钥
    private static final String APP_PRIVATE_KEY = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCS1LnMAaTi1x7uKCtP2FcDXS+HMwGdDoIaNuYbQl4sxoJivgGAEMpkO7KnULDUJUzNPGG+wADzq/bmTikdLeUdHsu315CE8DhB3PN/ns5Qjcy2/PEa6XjxBkYGrhq3UCEZ0FVGG9B+N8ObjZjBR3M+FjLnpCRDIWwUFKgw1mFRt6rOEvcq4U834rpabXBVN0K2SWhg3lIkAaoQPcDg7m1PZUupU8gd/sV3O4KMTtH0sYbk0Q1VBfUQFJXuVzOF0iVSxjIi/TwRk6V3WjoXrTmzxQuLhOyQWO31DxZgsl35ARTnbUFffqPkOu7t1ZyxCXey4gJIgd7U5rDPn9RLJPNhAgMBAAECggEAISkb4QAKDhUJbj3yMjEozaCxCDazyZWqOmNlqohdnn0im0xQKG0iWGrHGVR26yKVatCVPrA8RsvykebbEDT6Ro5a8eUkRXG/MtjEwXDLJZQwxK7xgONzpfOFwyJ09CuLnjnX2GKVvru3WJ0s/5G0bDQ1QO1oJyUYNJzJs2XnSr35Px03s2ogKiSlpv22Q1AWyi+KUylTmigPLWMsN77/hhcmsn/DJrydIDXlfiUp+0WtgXs7WLDDxNO4AmAmNflgy11PVm4v+mZxE2IJtVGouPI2lZ2wPMhSo3U77uhMHPQK0ff4RHzcotro4VW1bVpEg0XYIprIQXzXEDLIU4P/MQKBgQDVue4rueep4JzzDgQhTR/T2stDg416ie6auR4HgcYXt2wZ7UjNKfSHAHVPoULN+kyNm7V81GDWLCEf0ILWQso7Gx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T2VLqVPIHf7FdzuCjE7R9LGG5NENVQX1EBSV7lczhdIlUsYyIv08EZOld1o6F605s8ULi4TskFjt9Q8WYLJd+QEU521BX36j5Dru7dWcsQl3suICSIHe1Oawz5/USyTzYQIDAQAB";
    // 格式
    private static final String FORMAT = "json";
    // 字符集
    private static final String CHARSET = "UTF-8";
    // 版本
    private static final String VERSION = "1.0";
    // 签名类型
    private static final String SIGN_TYPE = "RSA2";

    public String startPay(String orderId, String totalAmount) throws AlipayApiException {
        // 创建客户端
        AlipayClient alipayClient = new DefaultAlipayClient(
                ALIPAY_GATEWAY,
                APP_ID,
                APP_PRIVATE_KEY,
                FORMAT,
                CHARSET,
                ALIPAY_PUBLIC_KEY,
                SIGN_TYPE);

        // 创建API请求
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl("付款成功后的同步通知页面");
        alipayRequest.setNotifyUrl("付款成功后的异步通知页面");

        // 设置请求参数
        alipayRequest.setBizContent("{" +
                "\"out_trade_no\":\"" + orderId + "\"," +
                "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
                "\"total_amount\":\"" + totalAmount + "\"," +
                "\"subject\":\"商品标题\"," +
                "\"body\":\"商品描述\"," +
                "\"timeout_express\":\"30m\"" +
                "}");

        // 发起支付
        String result = alipayClient.pageExecute(alipayRequest).getBody();

        // 返回支付页面
        return result;
    }
}